<template>
  <div>
    <div class="node" v-has="{action: 'iot:device:list', effect: 'move'}">
    <div :class="[$style.search_box, $style.topSelect]">
      <div :class="$style.selectBox" style="margin-right:20px;display: flex;align-items: center;">
        <label>时间段：</label>
        <el-date-picker
          v-model="appointmentTime"
          type="monthrange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM"
          :picker-options="pickerOptions"
          style="height:40px"
        ></el-date-picker>
      </div>
      <div :class="$style.selectBox">
        <el-button size="small" plain  icon="el-icon-search" @click="getIotDecive">查询</el-button>        
      </div>
    </div>
    <Panel title="直购电价">
      <div slot='ext' :class="$style.examine">
        <el-button v-has="{action: 'iot:device:add', effect: 'move'}"  class="button-offt" type="success" icon="el-icon-plus" @click="()=>editStore()">新增</el-button>
    </div>
    <TableEncapsulation
      slot="body"
      :tableConfig="tableConfig"
      :tableData="tableData"
    >
    <template slot="operation" slot-scope="operation">
          <el-button size="mini" icon="el-icon-edit"
            v-has="{action: 'iot:device:update', effect: 'move'}"
            @click="()=>editStore(operation.row)"
          >编辑</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete"
            v-has="{action: 'iot:device:delete', effect: 'move'}"
            @click="()=>remove(operation.row.time)"
          >删除</el-button>
        </template>
        <TablePager
          slot="pager"
          v-if="pager.use"
          :size="pager.size"
          :pageChange="pageChange"
          :show-total="pager.showTotal"
          :total="pager.total"
          :current="pager.current"
        >
          <span class="demonstration">GO></span>
        </TablePager>
    </TableEncapsulation>
    </Panel>
    
    <!-- 添加编辑 start-->
    <ModalPanel 
      :visible='visible'
      title="添加/编辑"
      :onCancel="onCancel"
      :class="$style.bannerDialog"
      :onOk="onSubmit">
      <div>
        <ModifyForm
          :editColumn='editColumn'
          :updateData="updateData"
           :hiddenBtn='true'
          labelWidth='100px'
          ref="configModal"
          :class="$style.ModifyForm"
          :temporaryData='modalData'>
          <div slot="box">
            <el-date-picker
              v-model="time"
              value-format="yyyy-MM"
              type="month"
              placeholder="选择月">
            </el-date-picker>
          </div>
        </ModifyForm>
      </div>
    </ModalPanel>
    <!-- 添加编辑end -->
    </div>
    <div style="display: none;width:100%;height:100%;margin: auto;" v-has="{action: 'iot:device:list', effect: 'noPremiss'}">
      <NoPremission />
    </div>
  </div>
</template>
<script>
import request from "@/tools/request";
import Panel from "@/components/Panel";
import TableEncapsulation from "@/components/TableEncapsulation";
import TablePager from "@/components/Pager";
import SearchInput from "@/components/SearchInput";
import { objectFilter } from "@/tools/array";
import ModifyForm from "@/components/ModifyForm";
import ModalPanel from "@/components/ModalPanel";
import NoPremission from "@/components/NoPremission";
export default {
  name: "purchase",
  components: {
    TableEncapsulation,
    TablePager,
    Panel,
    SearchInput,
    ModifyForm,
    ModalPanel,
    NoPremission
  },
  data() {
    return {
      tableData: [],
      formSku: {
        foodSkuSpeciftcations: [{'time':'','electric':''}],
      },
      searchs: {
        component: 'device',
        company:"",
        phone:"",
        name: '',
      },
       pager: {
        component: 'device',
        use: true,
        total: 0,
        current: 1,
        size: 10,
        showTotal: true
      },
      operation: true,
      appointmentTime: [],
      //添加编辑
      time: '',
      visible:false,
      modalData:{},
      editColumn: [
        {
          name: "时间(月)",
          prop: "name",
          type: "other",
          width:24,
          slotName: 'box',
          required: false
        },
        {
          name: "峰段电价",
          prop: "feng",
          type: "number",
          width:24,
          required: true,

        },
        {
          name: "平段电价",
          prop: "ping",
          type: "number",
          width:24,
          required: true,

        },
        {
          name: "谷段电价",
          prop: "gu",
          type: "number",
          width:24,
          required: true,

        },
        {
          name: "尖段电价",
          prop: "jian",
          type: "number",
          width:24,
          required: true,

        },
      ],
      //添加编辑end
    };
  },
  created() {
    // this.searchsFnc()
    let now = new Date().getTime() + 3600 * 1000 * 24
    let year = new Date(now).getFullYear()
    let month = new Date(now).getMonth() +1
    let last = new Date().getTime() - 3600 * 1000 * 24 * 90
    let lastYear =  new Date(last).getFullYear() 
    let LastMonth = new Date(last).getMonth() +1
    LastMonth = LastMonth >9 ? LastMonth: '0'+LastMonth
    month = month >9 ? month: '0'+month
    console.log([ lastYear+'-'+LastMonth,year+'-'+month])
    this.appointmentTime = [ lastYear+'-'+LastMonth,year+'-'+month]
    
  },
  mounted(){
    this.getIotDecive();
  },
  computed: {
    tableConfig () {
      return {
        selection: true,
        columnConfig: [
          {
            label: "时间",
            type: "text",
            prop: "time",
            align: "center"
          },
          {
            label: "峰段电价",
            type: "text",
            prop: "feng",
            align: "center"
          },
          {
            label: "平段电价",
            type: "text",
            prop: "ping",
            align: "center"
          },
          {
            label: "谷段电价",
            type: "text",
            prop: "gu",
            align: "center"
          },
          {
            label: "尖段电价",
            type: "text",
            prop: "jian",
            align: "center"
          },
          this.operation && {
            type: "operation",
            align: "center",
            label: "操作",
            width:240
          }
        ].filter(Boolean)
        }
    }
  },
  methods: {
    // searchsFnc (){
    //   let searchs = this.$store.getters.searchs
    //   if(searchs &&searchs.component == 'device'){
    //     this.searchs = searchs
    //   }
    //   let pager = this.$store.getters.pager
    //   if(pager &&pager.component == 'device'){
    //     this.pager = pager
    //   }
    // },
    async getIotDecive() {
      console.log('appointmentTime',this.appointmentTime)
      let startTime = this.appointmentTime[0]
      let endTime = this.appointmentTime[1]
      let page = this.pager.current
      console.log('page',page)
      let search = objectFilter({startTime, page, endTime})
      const res = await request({
        url: "/direct/purchase/list",
        method: "POST",
        data:  search
      });
      let data =res.page.list
      let arr = []
      data.map(item=> {
        var feng='', ping ='', gu='',jian =''
        item.list.map(val=> {
          if(val.type==1){
            jian =val.price
          }else if(val.type==2){
            feng = val.price
          }else if(val.type==3){
            ping = val.price
          }else{
            gu = val.price
          }
        })
        arr.push({time: item.time, feng, ping, gu , jian})
      })
      console.log('arr',arr)
      this.tableData = arr
      this.pager.total = res.page.totalCount
      this.pager.current = res.page.currPage
    },
    pageChange(val) {
      this.pager.current = val;
      this.getIotDecive();
    },

    changeSearch(key, val) {
      this.searchs[key] = val;
      this.pager.current = 1;
    },
    
    commentDetail(id){
      this.$store.commit('saveSearchs', this.searchs)
      this.$store.commit('savePager', this.pager)
      this.$router.push({ path: "/storeDetail",query:{id:id,type: "toview"} })
    },
    //添加编辑start
    editStore(rowData){
      if(rowData){
        console.log('rowData',rowData)
        this.time = rowData.time
        this.modalData = {...rowData}
      }else{
        this.modalData ={}
      }
      this.visible = true
    },
    async onSubmit(){
      this.$refs['configModal'].onSubmit()
    },
    onCancel(){
      this.visible = false
    },
    async updateData(values){
      console.log('values',values)
      // return
      const {feng, ping, gu, jian, id } = values
      let time = this.time
      if(!time){
        this.$message.error('请选择时间')
        return
      }
     let url = id ? "/direct/purchase/add" : "/direct/purchase/add"
     let msg = id ? "编辑成功" : "添加成功"
     let arr= [{type: 1, price: jian} , {type: 2, price: feng}, {type: 3, price: ping}, {type: 4, price: gu}]
     let res = await request({
       url: url,
       method: "POST",
       data: {time, list:arr}
     })
     if(res.code !==0) return
      this.$message.success(msg)
      this.visible = false
      this.getIotDecive();
    },
    //添加编辑end
    remove(id){
       this.$confirm('确认删除吗', '操作确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( async () => {
       let res = await request({
          url: '/direct/purchase/delete',
          method: 'POST',
          // dataType: 'json',
          data:{time: id}
        })
        if(res.code !==0) return
        this.$message.success('删除成功')
        if(this.tableData.length===1 && this.pager.current>1)
          this.$set(this.pager,'current', this.pager.current-1)
        this.getIotDecive()
      })
    },
  }
}
</script>
<style lang='scss' module>
.examine{
    display: flex;
    align-items: center;
    :global{
        div{
            color: #fff;
            padding: 10px;
            margin: 0 10px;
            border-radius: 2px;
            font-size: 14px;
            cursor: pointer;
            min-width: 60px;
            text-align: center;
        }
        .adopt{
                background: #409EFF;
        }
    }
}
.search_box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  :global {
    .el-input {
      width: 150px;
    }
    .el-select {
      .el-input {
        width: 90px;
      }
    }
    .el-input__icon {
      line-height: 27px;
    }
    .el-range-separator{
      line-height: 26px;
    }
  }
}

.topSelect {
  background-color: white;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}
</style>